package 顺序打印ABC;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Copyright (C) 2023 思创数码科技股份有限公司
 * <p/>
 * 版权所有
 * <p/>
 * 类名　　  : 三个线程顺序执行
 * 功能概要  :
 *
 * @Author : yangwk
 * @Date : 2024/4/2 22:27
 */
public class SynchronizedImpl {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.submit(new ThreadA());
        executorService.submit(new ThreadB());
        executorService.submit(new ThreadC());
        Thread.currentThread().join(1000000);
    }

    static String threadNameA = "A";
    static String threadNameB = "B";
    static String threadNameC = "C";
    static final AtomicInteger atomicInteger1 = new AtomicInteger(1);

    static class ThreadA implements Runnable {
        @Override
        public void run() {
            while (true) {
                synchronized (atomicInteger1) {
                    while (atomicInteger1.get() % 3 != 1) {
                        try {
                            atomicInteger1.wait();

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(threadNameA);
                    atomicInteger1.incrementAndGet();
                    atomicInteger1.notifyAll();
                }
            }

        }
    }

    static class ThreadB implements Runnable {

        @Override
        public void run() {
            while (true) {
                synchronized (atomicInteger1) {
                    while (atomicInteger1.get() % 3 != 2) {
                        try {
                            atomicInteger1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(threadNameB);
                    atomicInteger1.incrementAndGet();
                    atomicInteger1.notifyAll();

                }
            }
        }
    }

    static class ThreadC implements Runnable {

        @Override
        public void run() {
            while (true) {
                synchronized (atomicInteger1) {
                    while (atomicInteger1.get() % 3 != 0) {
                        try {
                            atomicInteger1.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(threadNameC);
                    atomicInteger1.incrementAndGet();
                    atomicInteger1.notifyAll();
                }
            }
        }
    }

}
